<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { $t } from '@vben/locales';
import { Page ,useVbenDrawer, useVbenModal,z} from '@vben/common-ui';
import { useTabs } from '@vben/hooks';

import { FeaturesDeawer,BannerDeawerview } from './components';
import { identity, useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
  TreeSelect,
  Button
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { getPageInfo_news, postPage_news, putPage_news } from '#/api/portal/carmodel';
import { getPage_news as getPage_banner } from '#/api/portal/vechilebanner'
import { getTreeByCode } from '#/api/portal/category';
import { usePreferencesStore } from '#/store';
import {getPage_news } from '#/api/portal/vechiledetail';

const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();
const newsOptions = ref([])
const bannerOptions = ref([])
const index: any = computed(() => {
  return route.params?.id ?? -1;
});
const router = useRouter();


const categoryTree =ref([])

const onSearchNews = async () => {

 const res = await getPage_news({car_model:(index.value==0?-1:index.value)});

  // newsOptions.value = (res?.data?.list || []).map(item => ({
  //   label: item.post_title,
  //   value: item.id,
  // }))
   newsOptions.value = (res?.data?.list || [])


 const res1 = await getPage_banner({car_model:(index.value>0?index.value:-1)});
  bannerOptions.value=(res1?.data?.list?.[0] || [])
}

const getTreeByCodes = async () => {
 const res = await getTreeByCode({ code: 'product' });

  categoryTree.value = res.data || [];
 

}
  
const handleSearch = async (value) => {
 const res1 = await getPage_banner({keyword:value,page:1,limit:15});
  bannerOptions.value=(res1?.data?.list || []).map(item => ({
    label: item.title,
    value: item.id,
  }))

}


const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
const pageTitle =
  Number.parseInt(index.value, 10) === 0
    ? `新增${routeTitle}`
    : `No.${index.value} - 编辑${routeTitle}`;
setTabTitle(pageTitle);
useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    post_title: '',
    post_alias: '',
    more: {
      thumbnail: '',
    },
  },
  pageThemeFiles: [],
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,

  resetButtonOptions: {
    show: false,
  },
  commonConfig: {
    labelWidth: 200,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },

    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.news_title;
          state.form.name = values.name;
          state.form.slug = values.slug;
          state.form.title = values.title;
          state.form.des = values.des;
          state.form.images = values.images;
          state.form.size = values.size;
          state.form.category_id = values.category_id;
          state.form.banner_id = values.banner_id
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'slug',
          'size',
          'name',
          'des',
          'images',
          'category_id',
          'banner_id'
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'name',
      label: $t('page.common.Model'),
      rules: z.string().max(30,'标题不能超过30'),
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'slug',
      label: $t('page.common.Slug'),
      rules: z.string({
          required_error: '别名不能为空',
          invalid_type_error: '别名格式不正确',
        })
        .min(1, '别名不能为空')
        .max(50, '不能超出50个字符')
        .regex(/^[\u4e00-\u9fa5\w-]+$/, '只能包含中英文、数字、_或-')
    },

    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Select'),
      },
      fieldName: 'des',
      label: $t('page.menu.'+routeTitle)+$t('page.common.Description'),
    },
     {
        component: 'TreeSelect',
      
        fieldName: 'category_id',
        label: $t('page.common.Please Select')+' '+$t('page.common.Category'),
        rules:'required'
        },
     {
          component: 'Select',
          defaultValue: '',
          fieldName: 'size', // 可选：字段名，视情况添加
          label: $t('page.common.Size'),         // 可选：标签名
          componentProps: {
            class: 'w-full',
            options: [
              {
                label: 'MID-SIZE MODELS',
                value: 'MID-SIZE MODELS'
              },
              {
                label: 'FULL-SIZE MODELS',
                value: 'FULL-SIZE MODELS'
              },
              {
                label: 'SSV-SIZE MODELS',
                value: 'SSV-SIZE MODELS'
              },
              {
                label: 'HYBRID MODELS',
                value: 'HYBRID MODELS'
              }
            ]
          },
         
     },


         


      // {
      //   component: 'Select',
      //   fieldName: 'banner_id',
      //   label: `车型banner`,
      //   componentProps: {
      //       class: 'w-full',
      //       placeholder: '选择幻灯片',
      //       options: bannerOptions,
      //       allowClear: true,
      //       showSearch: true,
      //       filterOption: false, // 不使用本地过滤
      //       onSearch: handleSearch, // ✅ 绑定搜索触发事件
      //   },
      
      // },  

    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
        tips:'800px-800px'
      },
      fieldName: 'images',
      label: $t('page.menu.'+routeTitle)+" "+$t('page.common.Thumbnail'),
    },

  ],
});

async function onSubmit() {
  const values: any = state.form;

  let response;

  if (values.id) {

     values.vechile_banner_data=vechile_banner_data.value;
    values.banner_data = bannerOptions.value;
    response = await putPage_news(values);
  } else {
    delete values.id;
    values.vechile_banner_data=vechile_banner_data.value;
    values.banner_data = bannerOptions.value;
    response = await postPage_news(values);
  }

  const { code, msg } = response;

  if (code === 1) {
    message.success(msg || '操作成功');
    closeCurrentTab();
    router.push({ name: 'Portalcarmodel' });
  } else {
    message.error(msg || '操作失败'); 
  }
}


async function onGetPage(id: number) {
  const { data } = await getPageInfo_news({ id });
  data.post = {
    id: data?.id ?? undefined,
    title: data?.title ?? '',
    slug:data?.slug??'',
    name: data?.name ?? '',
    des: data?.des ?? '',
    images: data?.images ?? [],
    size:data?.size?? '',
    category_id:data?.category_id??'',
    banner_id:data?.banner_id??''
  };
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form});
  state.pageThemeFiles = data.pageThemeFiles;
}

onMounted(async () => {
  if(index.value>0){
          await onGetPage(index.value);
  }

  await onSearchNews();
  await getTreeByCodes();

 
});


const vechile_banner_data=ref([]);
const [featuresDrawer, featuresDrawerApi] = useVbenDrawer({
    // 连接抽离的组件
  connectedComponent: FeaturesDeawer,

  onBeforeClose: () => {
    const drawerData = featuresDrawerApi.getData();
    vechile_banner_data.value = drawerData.tableData
    newsOptions.value= drawerData.tableData

    
  },
})

function handleExtra() {

  featuresDrawerApi.setState({
    title: `车系特征banner`,
  });

  featuresDrawerApi.setData({ id: index.value ,vechiledetal:  newsOptions.value});
  featuresDrawerApi.open();
}







////////////banenr

const banner_data=ref([]);
const [bannerDrawer, bannerDrawerApi] = useVbenDrawer({
    // 连接抽离的组件
  connectedComponent: BannerDeawerview,

  onBeforeClose: () => {
     const drawerData = bannerDrawerApi.getData();
      banner_data.value = drawerData;
      bannerOptions.value =drawerData?.bannerOptions||drawerData; 
  },
})

function handleExtraBanner() {
  bannerDrawerApi.setState({
    title: `车系banner`,
  });
  console.log('bannerOptions.value',bannerOptions.value)
  bannerDrawerApi.setData({ id: index.value ,bannerOptions:bannerOptions.value});
  bannerDrawerApi.open();
}


</script>

<template>
  <Page>
    <Card :title="$t('page.menu.'+routeTitle)+' '+ $t('page.common.Details')">

        <template #extra>
           <Button class="mr-4" type="primary" @click="handleExtraBanner()">
              {{$t('page.common.Model')}} banner
            </Button>
            <Button class="mr-4" type="primary" @click="handleExtra()">
              {{$t('page.common.Vehicle Features')}} banner
            </Button>

            
           
      </template>


      <BasicForm>
        <template #category_id="slotProps">

             <TreeSelect
                    v-bind="slotProps"
                    :field-names="{
                            value: 'id',
                            key: 'id',
                            label: 'name',
                            children: 'children',
                    }"
                    :tree-data="categoryTree"
                    allow-clear
                    placeholder="选择分类"
                    style="width: 100%"
                    tree-default-expand-all
                    tree-node-filter-prop="label"
                />

            </template>
          </BasicForm>
    </Card>
    <featuresDrawer/>
    <bannerDrawer/>
  </Page>
</template>
